/**
 * 拾取位置点
 * @param {Object} px 屏幕坐标
 * @return {Object} Cartesian3 三维坐标
 */
import * as Cesium from "cesium";

export function getCatesian3FromPX(viewer, px) {
  if (viewer && px) {
    var picks = viewer.scene.drillPick(px);
    var cartesian = null;
    var isOn3dtiles = false,
      isOnTerrain = false;
    // drillPick
    for (let i in picks) {
      let pick = picks[i];

      if (
        (pick && pick.primitive instanceof Cesium.Cesium3DTileFeature) ||
        (pick && pick.primitive instanceof Cesium.Cesium3DTileset) ||
        (pick && pick.primitive instanceof Cesium.Model)
      ) {
        //模型上拾取
        isOn3dtiles = true;
      }
      // 3dtilset
      if (isOn3dtiles) {
        viewer.scene.pick(px); // pick
        cartesian = viewer.scene.pickPosition(px);
        if (cartesian) {
          let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
          if (cartographic.height < 0) cartographic.height = 0;
          let lon = Cesium.Math.toDegrees(cartographic.longitude),
            lat = Cesium.Math.toDegrees(cartographic.latitude),
            height = cartographic.height;
          cartesian = transformWGS84ToCartesian(viewer,{
            lng: lon,
            lat: lat,
            alt: height
          });
        }
      }
    }
    // 地形
    let boolTerrain =
      viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider;
    // Terrain
    if (!isOn3dtiles && !boolTerrain) {
      var ray = viewer.scene.camera.getPickRay(px);
      if (!ray) return null;
      cartesian = viewer.scene.globe.pick(ray, viewer.scene);
      isOnTerrain = true;
    }
    // 地球
    if (!isOn3dtiles && !isOnTerrain && boolTerrain) {
      cartesian = viewer.scene.camera.pickEllipsoid(
        px,
        viewer.scene.globe.ellipsoid
      );
    }
    if (cartesian) {
      let position = transformCartesianToWGS84(viewer,cartesian);
      if (position.alt < 0) {
        cartesian = transformWGS84ToCartesian(viewer,position, 0.1);
      }
      return cartesian;
    }
    return false;
  }
}
/***
 * 坐标转换 84转笛卡尔
 */
function transformWGS84ToCartesian(viewer, position, alt) {
  if (viewer) {
    return position
      ? Cesium.Cartesian3.fromDegrees(
        position.lng || position.lon,
        position.lat,
        (position.alt = alt || position.alt),
        Cesium.Ellipsoid.WGS84
      )
      : Cesium.Cartesian3.ZERO;
  }
}
/***
 * 坐标转换 笛卡尔转84
 */
function transformCartesianToWGS84(viewer, cartesian) {
  if (viewer && cartesian) {
    var ellipsoid = Cesium.Ellipsoid.WGS84;
    var cartographic = ellipsoid.cartesianToCartographic(cartesian);
    return {
      lng: Cesium.Math.toDegrees(cartographic.longitude),
      lat: Cesium.Math.toDegrees(cartographic.latitude),
      alt: cartographic.height
    };
  }
}
